package com.peg.rules;

import com.peg.dataobjects.Context;

/**
 * @author sad
 */
public class ZeroOrMore extends ContainerRule {

    private int iterationsCount = 0;

    public ZeroOrMore() {
    }

    public ZeroOrMore(Rule rule) {
        setRule(rule);
    }

    @Override
    public boolean execute(Context context) {
        iterationsCount = 0;
        while (true) {
            Rule r=getRule();
            boolean result = executeRule(r, context);
            if (result == false) {
                break;
            }

            iterationsCount++;
        }

        return true;
    }

    @Override
    public void endRule(boolean result, Context context) {
        if (result) {
            context.setLastIterationsCount(iterationsCount);
        }
    }

    @Override
    public String toString() {
        return "ZeroOrMore";
    }
}
